// pages/addresslist/addresslist.js
var app = getApp(), areaJson = require("../../utils/Area.js"), fetchApi = require("../../utils/httpPost.js");
import Notify from '../../component/vant/notify/notify';
import Toast from '../../component/vant/toast/toast';
import Dialog from '../../component/vant/dialog/dialog';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgurl: app.getImgUrl(),
    type:0,
    netWork:false,
    hasData:true,
    dataList:[],
    addressAdd:false,
    showPhoneNumErr:false,
    isdefault:false,
    detail_address:'',
    real_name:'',
    addressName:'',
    phone_num:'',
    room_areas:'',
    room_no:'',
    showPickerView:false,
    addid:0,
    isedit:false,
    address:{},
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      console.log('地址列表',options)
    if(options.type){
      this.data.type = parseInt(options.type);
    }
    this.onHttpInit()
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpInit: function () {
    var that = this
    fetchApi.httpPost('/wxUser/address/list', {}, function (res) {
      console.log("地址列表数据", res)
      var totalcount = res.data.totalcount
      if (totalcount > 0) {
        that.setData({
          dataList: res.data.data.addresses,
        })
      }
      
      that.setData({
        netWork: true, hasData: totalcount > 0? true:false
      })
    }, function () {
        that.setData({ netWork: false, hasData: false })
    })
  },
  openPickerView: function () {
    this.setData({showPickerView: true });
  },
  //获取用户定位授权，地图选点
  chooseLocation: function () {
    var that = this;
    wx.getSetting({
      success:res=>{
        if(!res.authSetting['scope.userLocation']){
          wx.authorize({ 
            scope: 'scope.userLocation', 
            success:res=>{
            },fail:res=>{
              wx.showModal({
                title: '提示',
                content: '系统需要获取该您当前的定位，请确保您的位置授权已开启',
                showCancel: false,
                success: res=>{
                  if (res.confirm) {
                    wx.openSetting({
  
                    })
                  }
                }
              })
            }
          });
        }
        wx.chooseLocation({ 
          success: res=>{
            console.log(res)
            if(res.address!='' && res.name!=''){
              this.setData({
                detail_address: res.address + res.name,
              })
              that.data.detail_address = res.address + res.name;
              that.data.lng = res.longitude;
              that.data.lat = res.latitude;
            }
          }
        })
      }
    })
  },
  bindNameInput: function (t) {
    this.data.real_name = t.detail;
    this.setData({ real_name: t.detail});
  },
  bindAddressInput(t){
    this.data.detail_address = t.detail;
  },
  roomNoInput(e){
    this.data.room_no = e.detail;
  },
  phoneNumInput(e){
    this.data.phone_num = e.detail;
  },
  roomAreaInput(e){
    console.log('roomAreaInput',e);
    this.data.room_areas = e.detail;
    console.log('this.data.room_areas',this.data.room_areas)
  },
  pushToEdit:function(e){
    console.log('pushToEdit e',e )
    var that  = this;
    var itemdata = e.currentTarget.dataset.addressdata;
    console.log('pushToEdit itemdata',itemdata);
    that.data.addid = itemdata.id;
    if(this.data.type == 1) {
      this.data.isdefault = 1;
      this.data.detail_address = itemdata.address;
      this.data.real_name = itemdata.receiverName;
      this.data.phone_num = itemdata.phoneNum;
      this.data.isedit = true;
      this.data.address = itemdata;
      that.bindSaveButton();
    } else { 
      that.data.isedit = true;
      that.setData({
        addressAdd:true,
        room_no: itemdata.roomNo,
        room_areas: itemdata.roomAreas,
        real_name: itemdata.receiverName,
        phone_num: itemdata.phoneNum,
        addressName: itemdata.provCity,
        detail_address: itemdata.address,
        isdefault: itemdata.isDefault,
      })
    }
  },
  bindEditButton:function(e){

  },
  bindDelBnt:function(e){
    console.log('bindDelBnt',e)
    var address_id = e.currentTarget.dataset.id;
    var that = this;
    var message = "是否要删除该地址？"
    Dialog.confirm({
      title: '删除地址',
      message
    }).then(() => {
      that.onHttpDelAddress(address_id)
    })
    .catch(() => {
      Dialog.close();
    });
  },
  onHttpDelAddress(address_id){
    var that = this;
    console.log('onHttpDelAddress',address_id)
    if(address_id > 0){
      fetchApi.httpPost("/wxUser/address/delete", {
        address_id: address_id,
      }, function (res) {
        var code = res.data.code
        if (code == 0) {
          Toast.success(res.data.msg); 
          that.onHttpInit()
        } else {
          Toast.fail(res.data.msg); 
          return;
        }
      },function(){ })
    }
  },
  bindAddressAdd:function(){
    this.setData({
      real_name: "",
      phone_num: "",
      detail_address: "",
      addressName: "",
      value: [0, 0, 0],
      tempValue: [0, 0, 0],
      id: "",
      isdefault: !1,
      addressAdd: !0,
      addType: 0
    });
  },
  bindChange: function (t) {
    var that = this
    var a = t.detail.value;
    a[0] != that.data.tempValue[0] && (a = [a[0], 0, 0]), a[1] != that.data.tempValue[1] && (a = [a[0], a[1], 0]),
      that.setData({ 
        tempValue: a, value: a,
        cityArr: areaJson.result[a[0]].city,
        areaArr: areaJson.result[a[0]].city[a[1]].area
      });
  },
  confirmPickerView: function () {
    var t = this.data.value, 
    a = areaJson.result[t[0]].name + areaJson.result[t[0]].city[t[1]].name
                 + areaJson.result[t[0]].city[t[1]].area[t[2]].name, 
    s = areaJson.result[t[0]].id,
    d = areaJson.result[t[0]].city[t[1]].id, 
    i = areaJson.result[t[0]].city[t[1]].area[t[2]].id;
    this.setData({
      addressName: a,
      provId: s,
      cityId: d,
      areaId: i,
      showPickerView: false
    });
  },
  bindDefAddress: function () {
    this.setData({ isdefault: !this.data.isdefault });
  },
  bindPhoneNumInput: function (t) {
    var e = this.data.phone_num, a = /^1(2|3|4|5|6|7|8|9)\d{9}$/;
    console.log("手机号是否正确:", a.test(e))
    var istrue = a.test(e)
    if(!istrue){
      Notify("手机号格式不正确"); 
      return false;
    }else{
      this.data.showPhoneNumErr = true;
      return true;
    }
  },
  Trim: function (t, e) {
    for (var a = "", s = 0; s < t.length; s++) {
      var d = 1 * t[s];
      isNaN(d) || (a += t[s]);
    }
    var i = a.replace(/(^\s+)|(\s+$)/g, "");
    return "g" == e.toLowerCase() && (i = a.replace(/\s/g, "")), i;
  },
  bindCancelButton: function () {
    wx.setNavigationBarTitle({title: "地址管理"})
    this.setData({addressAdd: false});
  },
  bindSaveButton:function(){
    var that = this;
    if (that.data.detail_address == ''){
      Notify("请输入收货地址"); 
      return;
    }
    if (that.data.real_name == undefined || that.data.real_name == ''){
      Notify("请输入收件人姓名"); 
      return;
    }
    if (that.data.phone_num == undefined || that.data.phone_num == '') {
      Notify("请输入收件人手机号"); 
      return;
    }
    var ckPhone = that.bindPhoneNumInput();
    if(ckPhone){
      fetchApi.httpPost((!that.data.isedit ? '/wxUser/address/add' : '/wxUser/address/edit'), {
          addid:that.data.addid,
          address: that.data.detail_address,
          real_name: that.data.real_name,
          phone_num: that.data.phone_num,
          is_default: that.data.isdefault
        }, function (res) {
          console.log("添加地址相应数据", res)
          var code = res.data.code
          if (code == 0) {
            console.log('that.data.type',that.data.type)
            console.log('that.data.address', that.data.address)
            that.data.address = res.data.data;
            if(that.data.type == 1){
                var pages = getCurrentPages();
                var prevPage = pages[pages.length - 2]; //上一个页面
                prevPage.setData({
                  is_has_address:1,
                  address: res.data.data,
                })
                console.log('pages prevPage 2 ',prevPage)
                wx.navigateBack({
                  delta: -1,
                })
            }else{
                that.bindCancelButton()
                that.onHttpInit()
            }
          } else {
            Notify(res.data.msg); 
            return;
          }
        },function(){})
    }
  },
  bindDetailAddress: function (t) {
    this.setData({ detail_address: t.detail.value });
  },
  addNewAddress:function(){
    var that = this
    wx.chooseAddress({
      success: res => {
        fetchApi.httpPost((!that.data.isedit ? '/wxUser/address/add' : '/wxUser/address/edit'), {
          addid: that.data.addid,
          real_name: res.userName,
          phone_num: res.telNumber,
          provcity: res.provinceName + res.cityName + res.countyName,
          address: res.detailInfo,
          is_default: 0
        }, function (res) {
          var code = res.data.code
          if (code == 0) {
            that.bindCancelButton()
            that.onHttpInit()
          } else {
            Notify(res.data.msg); return;
          }
        },function(){ })
      },fail:res =>{ }
    })
  },
})